import React, {Component} from 'react';
import { Button, Input, Select,AutoComplete } from 'antd';
import { inVoiceSummary, applyInvoice, invoiceList, invoiceInfo } from '../../fetch/fetchApi';
import PropsType from "prop-types";
import locale from "antd/lib/date-picker/locale/zh_CN";
import {DatePicker, message} from "antd/lib/index";
const Option = Select.Option;
const { RangePicker } = DatePicker;

class ApplyInvoice extends Component {
  constructor (props) {
    super(props);
    this.props = props;
    this.state = {
      invoiceData: {
        count: 0,
        amount: 0,
        flag: null
      },
      loadingmes: '查询',
      loading: !1,
      postLoading: !1,
      invoiceMaterial: '1',
      businessType: '1',
      latestRecord:{

      },
      latestDetailInfo:{
		  invoiceMaterial:1,//发票类别：1纸质发票2电子发票
		  invoiceAmount:'',//开票金额
		  invoiceType:1,//发票类型：1普通发票2增值税发票
		  businessType:1,//开票类型
          type:1,//开票主体
		  invoiceTitle:'',//发票抬头
		  payerPhone: '',
		  payerAddress: '',
		  address: '',
		  phone: '',
		  name: '',
		  payerBank: '',
		  payerBankAccount: '',
		  payerRegisterNo: '',
      },
      type: '发票类型',
      invoiceTitle:'',
      payerPhone: '',
      payerAddress: '',
      address: '',
      phone: '',
      name: '',
      payerBank: '',
      payerBankAccount: '',
      payerRegisterNo: '',
    };
    this.init();
    if (window.LayoutTab) {
      this.query.userId = window.LayoutTab.tabParam.userId;
      this.query.account = window.LayoutTab.tabParam.account;
      this.param.userId = this.query.userId;
    }
  }

  init () {
    this.query = {};
    this.param = {
      userId: this.query.userId,
      invoiceMaterial: '1',
      businessType: '1'
    };
    this.invoiceList(this.param.userId,1,1);
    console.log('3333333333333')
  }
  //获取最近一次开票信息
	async invoiceList (userId,page,pagecount) {
		// this.setState({
		// 	loading: !0,
		// 	btnloading: !0
		// });
        let params={
          userId:userId,
          page:page,
          pagecount:pagecount
        }
		try {
			const resData = await invoiceList(params);
			let resObj = resData.data.data;
			let detailObj={
			  'invoiceId': resObj[0].invoiceId ,
              'invoiceAppkey': resObj[0].invoiceAppkey,
              'outInvoiceId': resObj[0].outInvoiceId
			}
			if (resData.data.code === '200') {
			  // this.setState({
				//   latestRecord:resObj[0]
              // })
				this.getInvoiceInfo(detailObj).then((data) => {
					this.setState({
						latestDetailInfo: data
					});
					this.param=Object.assign({},this.param,data)
				});
			}
		} catch (e) {
			console.log(e);
		}
	}
  // fetch 发票详情
  async getInvoiceInfo (obj) {
      try {
          const resData = await invoiceInfo(obj);
          if (resData.data.code === '200') {
              return resData.data.data;
          }
      } catch (e) {
          console.log(e);
      }
  }
  // 初始化开票数据
  async inVoiceSummary () {
    try {
      const resData = await inVoiceSummary(this.query);
      if (resData.data.code === '200') {
        return resData.data.data;
      }
    } catch (e) {
      console.log(e);
    }
  }

  // 打开tab
  openTab (param, e) {
    console.log('1111111111111')
    this.props.onAdd.bind(window.LayoutTab)(e, param);
  }

  // 选择日期
  onDataChange (e) {
    this.query['startDate'] = e[0] && e[0].format('YYYY-MM-DD').toString();
    this.query['endDate'] = e[1] && e[1].format('YYYY-MM-DD').toString();
  }

  // 提交查询
  queryChargeInfo () {
    this.setState({
      loading: !0
    });
    this.inVoiceSummary().then((data) => {
      this.setState({
        loading: !1,
        btnloading: !1,
        invoiceData: data || {
        count: 0,
        amount: 0,
        flag: null
      }
      });
      this.param['orderIds'] = this.state.invoiceData && this.state.invoiceData.orderIds;
      this.param['expressPayer'] = this.state.invoiceData && this.state.invoiceData.flag;
    });
  }

  // 注入材质参数
  materialInputChange (type) {
    console.log('materialInputChange',type)
    this.param['invoiceMaterial'] = type;
    type === '1' ? this.param['invoiceType'] = '2' : (this.param['invoiceType'] = '1');
    this.setState({
      type: type === '1' ? '增值税发票': '普通发票',
      invoiceMaterial: type.toString()
    });
  }

  // 注入主体参数
  businessInputChange (type) {
    console.log('businessType',type)
    this.param['businessType'] = type;
    this.setState({
      businessType: type.toString(),
    });
  }

  // 注入类型参数
  typeInputChange (type) {
    console.log('invoiceType',type)
    this.param['invoiceType'] = type;
    this.setState({
      type: type === '1' ? '普通发票': '增值税发票',
      invoiceType:type+''
    });
  }

  // 设置发票抬头参数
  titleInputHandler (e) {
    console.log('e=-----',e)
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{invoiceTitle: e})
	  });
    this.param['invoiceTitle'] = e;
  }

  // 设置税号
  dutyInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{payerRegisterNo: e})
    });
    this.param['payerRegisterNo'] = e;
  }

  // 设置开户账号
  bankAcInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{payerBankAccount: e})
    });
    this.param['payerBankAccount'] = e;
  }

  // 设置开户行
  bankInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{payerBank: e})
    });
    this.param['payerBank'] = e;
  }

  // 设置收件人
  nameInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{name: e})
    });
    this.param['name'] = e;
  }

  // 设置收件电话
  phoneInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{phone: e})
    });
    this.param['phone'] = e;
  }

  // 设置收件地址
  addressInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{address: e})
    });
    this.param['address'] = e;
  }

  // 设置注册地址
  companyAddressInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{payerAddress: e})
    });
    this.param['payerAddress'] = e;
  }

  // 设置公司电话
  payerPhoneInputHandler (e) {
    this.setState({
		latestDetailInfo:Object.assign(this.state.latestDetailInfo,{payerPhone: e})
    });
    this.param['payerPhone'] = e;
  }

  // 提交开票
  submitInvoice () {
    this.setState({
      postLoading: !0,
      // latestDetailInfo:{
		//   invoiceMaterial:this.state.invoiceMaterial,//发票类别：1纸质发票2电子发票
		//   invoiceType:this.state.invoiceType,//发票类型：1普通发票2增值税发票
		//   businessType:1,//开票类型
		//   type:this.state.businessType,//开票主体
		//   invoiceTitle:this.state.invoiceTitle,//发票抬头
		//   payerPhone: this.state.payerPhone,
		//   payerAddress: this.state.payerAddress,
		//   address: this.state.address,
		//   phone: this.state.phone,
		//   name: this.state.name,
		//   payerBank: this.state.payerBank,
		//   payerBankAccount:this.state.payerBankAccount,
		//   payerRegisterNo: this.state.payerRegisterNo,
      // }
    });
    this.applyInvoice().then((data) => {
      if (data.code === '200') {
        message.success('申请成功', 1);
        this.setState({
          latestDetailInfo:{
			  invoiceMaterial:1,//发票类别：1纸质发票2电子发票
			  invoiceAmount:'',//开票金额
			  invoiceType:1,//发票类型：1普通发票2增值税发票
			  businessType:1,//开票类型
			  type:1,//开票主体
			  invoiceTitle:'',//发票抬头
			  payerPhone: '',
			  payerAddress: '',
			  address: '',
			  phone: '',
			  name: '',
			  payerBank: '',
			  payerBankAccount: '',
			  payerRegisterNo: '',
          },
          invoiceData: {
            count: 0,
            amount: 0,
            flag: null
          }
        });
        this.param = {
          userId: this.query.userId,
          invoiceMaterial: '1',
          businessType: '1'
        };
      } else {
        message.warning(data.text, 1);
		  // this.setState({
			//   latestDetailInfo:{
			// 	  invoiceMaterial:1,//发票类别：1纸质发票2电子发票
			// 	  invoiceAmount:'',//开票金额
			// 	  invoiceType:1,//发票类型：1普通发票2增值税发票
			// 	  businessType:1,//开票类型
			// 	  type:1,//开票主体
			// 	  invoiceTitle:'',//发票抬头
			// 	  payerPhone: '',
			// 	  payerAddress: '',
			// 	  address: '',
			// 	  phone: '',
			// 	  name: '',
			// 	  payerBank: '',
			// 	  payerBankAccount: '',
			// 	  payerRegisterNo: '',
			//   }
		  // });
      }
      this.setState({
        postLoading: !1,
      });
    });
  }

  async applyInvoice () {
    console.log('param---',this.param)
    try {
      const resData = await applyInvoice(this.param);
      return resData.data;
    } catch (e) {
      console.log(e);
    }
  }

  render () {
    const Content = <div className="sc-page-content">
      <div className="page-panel">
        <div className={'page-info-item'}>
          <h3><span>开票金额</span></h3>
          <ul>
            <li>
              <Input type={'text'} disabled={true} value={this.query.account}/>
              <Input type={'text'} disabled={true} value={'充电订单开票'}/>
              <strong>订单结束时间:</strong>
              <RangePicker
                onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD" />
              <Button type="primary" onClick={this.queryChargeInfo.bind(this)} loading={this.state.loading}>{this.state.loadingmes}</Button>
            </li>
            <li>
              <strong>可开票订单：{this.state.invoiceData ? this.state.invoiceData.count : '0'}笔，可开票金额：{this.state.invoiceData ? this.state.invoiceData.amount : '0'}</strong>
            </li>
          </ul>
          <h3><span>开票信息</span></h3>
          <ul class="applyInvoice-ul">
            <li>
              <Select placeholder='发票材质' defaultValue={this.state.latestDetailInfo.invoiceMaterial+''} onChange={this.materialInputChange.bind(this)}>
                <Option value="2">电子发票</Option>
                <Option value="1">纸质发票</Option>
              </Select>
              <Select placeholder='开票主体' defaultValue={this.state.latestDetailInfo.type+''} onChange={this.businessInputChange.bind(this)}>
                <Option value="2">企业</Option>
                <Option value="1">个人</Option>
              </Select>
              <Select placeholder='发票类型'  defaultValue={this.state.latestDetailInfo.invoiceType+''} onChange={this.typeInputChange.bind(this)}>
                <Option value="1">普通发票</Option>
                {this.state.invoiceMaterial === '1' && <Option value="2">增值税发票</Option>}
              </Select>

                <AutoComplete  placeholder='输入发票抬头' value={this.state.latestDetailInfo.invoiceTitle}  onChange={this.titleInputHandler.bind(this)} />
            </li>
            {
              this.state.businessType === '2' &&
              <li>
                <AutoComplete  placeholder='请输入税号' value={this.state.latestDetailInfo.payerRegisterNo} defaultValue={this.state.latestDetailInfo.payerRegisterNo} onChange={this.dutyInputHandler.bind(this)}/>
                <AutoComplete  placeholder='请输入开户账号' value={this.state.latestDetailInfo.payerBankAccount} defaultValue={this.state.latestDetailInfo.payerBankAccount} onChange={this.bankAcInputHandler.bind(this)}/>
                <AutoComplete  placeholder='请输入开户行' value={this.state.latestDetailInfo.payerBank} defaultValue={this.state.latestDetailInfo.payerBank} onChange={this.bankInputHandler.bind(this)}/>
              </li>
            }
            {
              this.state.businessType === '2' &&
              <li>
                <AutoComplete  placeholder='请输入注册地址' value={this.state.latestDetailInfo.payerAddress}  onChange={this.companyAddressInputHandler.bind(this)}/>
                <AutoComplete  placeholder='请输入电话号码' value={this.state.latestDetailInfo.payerPhone}  onChange={this.payerPhoneInputHandler.bind(this)}/>
              </li>
            }
          </ul>
          { this.state.invoiceMaterial === '1' &&
          <div><h3><span>邮寄信息</span></h3>
          <ul>
            <li>
              <AutoComplete  placeholder='请输入收件人' value={this.state.latestDetailInfo.name}  onChange={this.nameInputHandler.bind(this)}/>
              <AutoComplete  placeholder='请输入联系电话' value={this.state.latestDetailInfo.phone} onChange={this.phoneInputHandler.bind(this)}/>
              <AutoComplete  placeholder='请输入收件地址' value={this.state.latestDetailInfo.address}  onChange={this.addressInputHandler.bind(this)}/>
            </li>
          </ul>
          <h3><span>运费支付</span></h3>
          <ul>
            <li>
              {this.state.invoiceData.flag !== null ? (this.state.invoiceData.flag === 0 ? '到付':'包邮') : '--'}
            </li>
          </ul></div>
            }
          <div className="box-single-btn">
            <Button type={'primary'} loading={this.state.postLoading} onClick={() => this.submitInvoice()}>提交开票</Button>
          </div>
        </div>
      </div>
    </div>;
    return Content;
  }
}

export default ApplyInvoice;

ApplyInvoice.propTypes = {
  onAdd: PropsType.func
}